package com.xuecheng.system.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.UserConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LoginDto;
import com.xuecheng.commons.model.vo.LoginVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.JwtUtils;
import com.xuecheng.system.domain.User;
import com.xuecheng.system.mapper.UserMapper;
import com.xuecheng.system.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.Security;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author HuangYuwu
 * @since 2022-09-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 用户登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        // 1.非空判断
        String username = dto.getUsername();
        String password = dto.getPassword();
        String utype = dto.getUtype();
        if (StrUtil.isBlank(username) ||  StrUtil.isBlank(password) ||  StrUtil.isBlank(utype)) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        // 2.根据username+utype查询数据库
        LambdaQueryWrapper<User>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,username);
        queryWrapper.eq(User::getUtype,utype);
        User user = this.getOne(queryWrapper);
        // 3.判断用户是否存在
        if (user==null){
            throw new BusinessException(ErrorCode.LOGINERROR);
        }
        // 4.判断密码是否正确
        String passwordMd5 = SecureUtil.md5(password);
        if (!StrUtil.equals(passwordMd5,user.getPassword())){
            throw new BusinessException(ErrorCode.LOGINERROR);
        }
        // 5.登录成功，jwt制作token
        Map map=new HashMap();
        map.put("userName",user.getName());
        map.put("userId",user.getId());
        map.put("companyId",user.getCompanyId());
        map.put("companyName",user.getCompanyName());
        String token = JwtUtils.createToken(map);
        // 6.user存入redis（敏感数据+有效期）
        redisTemplate.opsForValue().set(UserConstants.USER_ID+user.getId(),map,180, TimeUnit.MINUTES);
        // 7.返回结果
        LoginVo vo=new LoginVo();
        vo.setUsername(username);
        vo.setAccess_token(token);
        return ResponseResult.okResult(vo);
    }
}
